/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.tcc;

import com.inspur.edp.bef.api.action.tcc.TccHandlerContext;
import com.inspur.edp.bef.api.be.IBENodeEntityContext;
import com.inspur.edp.bef.core.be.BusinessEntity;
import com.inspur.edp.bef.core.be.CoreBEContext;
import com.inspur.edp.caf.transaction.api.annoation.tcc.BusinessActionContext;
import com.inspur.edp.cef.entity.changeset.DeleteChangeDetail;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;

public class TccHandlerContextImpl implements TccHandlerContext {

  private final IBENodeEntityContext beCtx;
  private final BusinessActionContext tccContext;
  private IChangeDetail reverseChg;

  public TccHandlerContextImpl(BusinessActionContext tccContext, IBENodeEntityContext beCtx, IChangeDetail reverseChg) {
    this.tccContext = tccContext;
    this.beCtx = beCtx;
    this.reverseChg = reverseChg;
  }

  public IBENodeEntityContext getBEContext() {
    return beCtx;
  }

  @Override
  public IEntityData getData() {
    return beCtx.getData();
  }

  @Override
  public BusinessActionContext getBusinessActionContext() {
    return tccContext;
  }

  @Override
  public String getDataId() {
    return beCtx.getID();
  }

  @Override
  public void deleteCurrentData() {
    if (getData() == null) {
      throw new RuntimeException("数据["+getDataId()+"]已被删除不可重复删除, 可能是一阶段数据已删除或一次二阶段执行过程中重复调用了此方法");
    }
    if (beCtx instanceof CoreBEContext) {
      ((CoreBEContext) beCtx).appendTempCurrentChange(new DeleteChangeDetail(beCtx.getID()));
    } else {
      beCtx.getParentContext().getCurrentData().getChilds().get(beCtx.getCode())
          .remove(getData().getID());
    }
  }

  @Override
  public IEntityData createChild(String childCode) {
    IEntityData childData = (IEntityData) getData().createChild(childCode);
    getData().getChilds().get(childCode).add(childData);
    return childData;
  }

  public IChangeDetail getReverseChg() {
    return reverseChg;
  }
}
